<?php
require_once(ABSPATH.'include/dao/mydao.php');
require_once(ABSPATH.'include/model/Category.php');

class categoriesDAO{
	function insert(&$vo){
	     $sql = "insert into categories(name,screen_name,notes,status,list_order,post_count)values(".
	     "'".$vo->name."',".
	     "'".$vo->screen_name."',".
	     "'".$vo->notes."',".
	     "'".$vo->status."',".
	     "'".$vo->list_order."',".
	     "'0')";
	     
	     $vo->id = mydao_insert($sql);
	}
	
	function update(&$vo){
	     $sql = "update categories set ".
	     "name='".$vo->name. "',".
	     "screen_name='".$vo->screen_name. "',".
	     "notes='".$vo->notes. "',".
	     "status='".$vo->status. "',".
	     "list_order='".$vo->list_order. "' ". 
	     "where id='".$vo->id. "'";
	     mydao_runSql($sql);
	}
	
	function set_status($id,$status){
		$sql="update categories set status=$status where id=$id";
		mydao_runSql($sql);
	}
	
	function get($id){
	     $sql="select id,name,screen_name,notes,status,list_order,post_count from categories where id=".$id;
	     return $this->convert(mydao_getLine($sql));
	}
	
	function get_all(){
		$sql="select id,name,screen_name,notes,status,list_order,post_count from categories order by list_order";
		return $this-> convertRows(mydao_getData($sql));
	}
	
	function getCategoryCount(){
		$sql='SELECT category_id,count(*) as count FROM posts group by category_id';
		return mydao_getData($sql);
	}
	private function convert($result){
	     $vo = new Category();
	     $vo->id = $result["id"];     
	     $vo->name = $result["name"];     
	     $vo->screen_name = $result["screen_name"];     
	     $vo->notes = $result["notes"];     
	     $vo->status = $result["status"];     
	     $vo->list_order = $result["list_order"];     
	     $vo->post_count = $result["post_count"];
	     return $vo;
	}
	
	private function convertRows($rows){
		$counts = $this->getCategoryCount();		
		$results = array();
	    foreach ($rows as $row){
	    	$c = $this->convert($row);	
	    	foreach($counts as $count){
	    		if($c->id==$count["category_id"]){
	    			$c->post_count = $count["count"];	    			
	    		}
	    	}    	
	    	array_push($results, $c);
	    }
	    return $results;
	}
}
?>